from uuid import uuid4

from app.schema.base import *
from app.utils.paste import paste_image
from app.service.base import BaseService
from app.schema.ai import AiInfoSchema,AiUpdateSchema
from app.utils.wxapp import WxappUtils
from app.utils.oss2_upload import Oss2UploadUtil
from app.schema.base import ListFilterSchema,ListArgsSchema,ListOrderSchema,RespIdSchema,RespBaseSchema,RespDataSchema
from ..dao.ai import AiDao
from ..dao.user import UserDao
from ..model.ai import Ai
from ..schema.auth import UserInfoSchema

class AiService(BaseService):
    def __init__(self, auth_data: UserInfoSchema = {}):
        user_id = auth_data.id
        self.Model = Ai
        self.dao = AiDao(user_id)
        self.dao.Model = Ai

        super().__init__(user_id, auth_data)
    
    async def create(self, ai_info:AiInfoSchema) -> RespIdSchema:
        try:
            ai_info.user_id=self.user_id
            ai_info.add_num=0
            ai_list=self.list(ListArgsSchema(filters=[ListFilterSchema(key='user_id',value=self.user_id,condition='=')]))
            ai_info.vector_name="a"+str(uuid4().hex)
            if ai_list.count>0:
                return RespBaseSchema(code=40001,message='用户已创建ai助手')
            ai= super().create(ai_info)
            data=await WxappUtils().getUnlimitedQRCode(page="pages/chat/index",scene=f"ai_id={ai.id}&from=share")
            user_info=UserDao().read(self.user_id)
            background=await Oss2UploadUtil().upload('img',ai_info.vector_name+'s',data)
            over_data = await paste_image(user_info.avatar, background)
            page=await Oss2UploadUtil().upload('img',ai_info.vector_name,over_data)
            update_info=AiUpdateSchema(id=ai.id,page=page)
            self.update(update_info)
            return RespBaseSchema()
        except:
            if ai:
                self.delete(ai.id)
            self.dao.db.sess.rollback()
            return RespBaseSchema(code=50001,message='创建失败')
